﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;

namespace Meow
{
    public class CompProperties_JobHediff : CompProperties
    {
        public List<JobDef> jobDefs = new List<JobDef>();

        public List<HediffDef> hediffDefs = new List<HediffDef>();

        public ThingDef targetRace;

        public int ticksToHediff;

        public float hediffSeverity;

        public string maxHediffSevertyMessage;

        public CompProperties_JobHediff()
        {
            compClass = typeof(ThingComp_JobHediff);
        }
    }



    public class ThingComp_JobHediff : ThingComp
    {
        private int ticksToHediff;

        public CompProperties_JobHediff Props => (CompProperties_JobHediff)props;

        public Pawn pawn { get; private set; }

        public override void CompTick()
        {
            if (pawn == null || !pawn.Spawned || pawn.def != Props.targetRace)
            {
                return;
            }

            base.CompTick();
            for (int i = 0; i < Props.jobDefs.Count; i++)
            {
                if (pawn?.jobs?.curJob?.def != Props.jobDefs[i])
                {
                    continue;
                }

                ticksToHediff--;
                if (ticksToHediff > 0)
                {
                    return;
                }

                for (int j = 0; j < Props.hediffDefs.Count; j++)
                {
                    HediffDef hediffDef = Props.hediffDefs[j];
                    Hediff hediff = HediffMaker.MakeHediff(hediffDef, pawn);
                    hediff.Severity = Props.hediffSeverity;
                    pawn.health.AddHediff(hediff);
                    if (Props.maxHediffSevertyMessage.NullOrEmpty())
                    {
                        continue;
                    }

                    foreach (Hediff hediff2 in pawn.health.hediffSet.hediffs)
                    {
                        if (hediff2.def == hediffDef && hediff2.Severity == 1f)
                        {
                            Messages.Message(Props.maxHediffSevertyMessage.Translate(pawn.def.LabelCap, pawn.LabelShort, Props.hediffDefs[j].label, hediff2.Severity).CapitalizeFirst(), pawn, MessageTypeDefOf.NeutralEvent);
                        }
                    }
                }

                ResetTicksToHediff();
                return;
            }

            ResetTicksToHediff();
        }

        public override void PostSpawnSetup(bool respawningAfterLoad)
        {
            base.PostSpawnSetup(respawningAfterLoad);
            pawn = parent as Pawn;
            ResetTicksToHediff();
        }

        private void ResetTicksToHediff()
        {
            ticksToHediff = Props.ticksToHediff;
        }
    }
}
